<?php

namespace app\api\model\wanlshop;

use app\admin\model\wanlshop\Packagerule;
use think\Db;
use think\Exception;
use think\Model;
use think\Request;
use traits\model\SoftDelete;

class Package extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'wanlshop_package';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'delivery_mode_text',
        'idcard_status_text',
        'delivery_status_text',
        'delivertime_text',
        'status_text'
    ];
    

    
    public function getDeliveryModeList()
    {
        return ['created' => __('Delivery_mode created'), 'self' => __('Delivery_mode self'), 'instead' => __('Delivery_mode instead')];
    }

    public function getIdcardStatusList()
    {
        return ['0' => __('Idcard_status 0'), '1' => __('Idcard_status 1')];
    }

    public function getDeliveryStatusList()
    {
        return ['0' => __('Delivery_status 0'), '1' => __('Delivery_status 1')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getDeliveryModeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delivery_mode']) ? $data['delivery_mode'] : '');
        $list = $this->getDeliveryModeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIdcardStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['idcard_status']) ? $data['idcard_status'] : '');
        $list = $this->getIdcardStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getDeliveryStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delivery_status']) ? $data['delivery_status'] : '');
        $list = $this->getDeliveryStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getDelivertimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delivertime']) ? $data['delivertime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setDelivertimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    protected function setPackageNoAttr($value)
    {
        return substr(time(),-8).substr(substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$value,-8);
    }

    public function wanlshoporder()
    {
        return $this->belongsTo('Order', 'order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function goods(){
        return $this->hasMany('app\api\model\wanlshop\Packagegoods', 'package_id', 'id');
    }


    public function shop()
    {
        return $this->belongsTo('Shop', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getImageAttr($value, $data){
        $request = Request::instance();
        if (substr($request->url(), 0, 4) == '/api') {
            $value = $value ? explode(',', $value) : [];
            $images = [];
            foreach ($value as $image) {
                $images[] = cdnurl($image, true);
            }
            return $images;
        }
        return $value;
    }


    // 分箱进包裹
    public function addPackage($order_id){
        Db::startTrans();
        $order = model('app\api\model\wanlshop\Order')->get($order_id,['goods'])->toArray();
        $address = model('app\index\model\wanlshop\OrderAddress')
            ->where(['order_id' => $order_id])
            ->order('isaddress desc')
            ->find();
        $city = explode('/',$address['address'])[1] ?? '';
        $rules = collection(Packagerule::all())->toArray();
        $packageClass = new \fast\Package($order['goods'],$rules);
        $packageList = $packageClass->buildPackage();
        $orderGoods = array_column($order['goods'],null,'goods_sku_id');
        $goodsList = $addressList = $packageData = [];
        foreach ($packageList as $list){
            foreach ($list as $item){
                $package = new Package();
                $package->order_id = $order['id'];
                $package->user_id = $order['user_id'];
                $package->shop_id = $order['shop_id'];
                $package->package_no = $order['shop_id'].$order['user_id'];
                $package->weight = $item['weight'];
                $packageFright = $this->freight($order['freight_id'],$item['weight'],1,$city);
                $package->freight_id = $packageFright['id'];
                $package->freight_price = $packageFright['price'];
                if($package->save()){
                    $package_price = $package_supply_price = $service_price = $settlement_price = 0;
                    foreach ($item['goods'] as $data){
                        // 商品列表 actual_payment
                        $goodsList[] = [
                            'order_id' => $order['id'], // 获取自增ID
                            'order_goods_id' =>$orderGoods[$data['sku_id']]['id'],
                            'package_id' => $package->id,
                            'goods_id' => $orderGoods[$data['sku_id']]['goods_id'],
                            'title' => $orderGoods[$data['sku_id']]['title'],
                            'shop_id' => $orderGoods[$data['sku_id']]['shop_id'],
                            'shop_name' => $orderGoods[$data['sku_id']]['shop_name'],
                            'image' => $orderGoods[$data['sku_id']]['image'],
                            'goods_sku_sn' => $orderGoods[$data['sku_id']]['goods_sku_sn'],
                            'goods_sku_id' => $orderGoods[$data['sku_id']]['goods_sku_id'],
                            'goods_sku_rule_id' => $orderGoods[$data['sku_id']]['goods_sku_rule_id'],
                            'weight' => $orderGoods[$data['sku_id']]['weight'],
                            'difference' => $orderGoods[$data['sku_id']]['difference'],
                            'price' => $orderGoods[$data['sku_id']]['price'],
                            'supply_price' => $orderGoods[$data['sku_id']]['supply_price'],
                            'market_price' => $orderGoods[$data['sku_id']]['market_price'],
                            'number' => $data['order_goods_number'],
                        ];

                        $package_price += bcmul($orderGoods[$data['sku_id']]['price'],$data['order_goods_number'],2);
                        $package_supply_price += bcmul($orderGoods[$data['sku_id']]['supply_price'],$data['order_goods_number'],2);
                        $service_price += 0;
                        $settlement_price +=  bcmul($orderGoods[$data['sku_id']]['price'],$data['order_goods_number'],2) - bcmul($orderGoods[$data['sku_id']]['supply_price'],$data['order_goods_number'],2);
                    }
                    // 生成地址
                    $addressList[] = [
                        'package_id' => $package->id,
                        'user_id' => $address['user_id'],
                        'shop_id' => $address['shop_id'],
                        'order_id'  => $address['order_id'],
                        'isaddress'  => $address['isaddress'],
                        'name' => $address['name'],
                        'mobile' => $address['mobile'],
                        'address' => $address['address'],
                        'address_name' => $address['address_name'],
                        'location' => $address['location'],
                        'image_front' => $address['image_front'],
                        'image_back' => $address['image_back'],
                        'number' => $address['number'],
                    ];
                    $package->package_price = $package_price;
                    $package->package_supply_price = $package_supply_price;
                    $package->service_price = $service_price;
                    $package->settlement_price = $settlement_price;
                    $package->save();
                }

            }
        }

        model('app\api\model\wanlshop\Packageaddress')->saveAll($addressList);
        model('app\api\model\wanlshop\Packagegoods')->saveAll($goodsList);
        Db::commit();
    }




    // 分箱进包裹
    public function addPackage1($order_id){
        Db::startTrans();
        $order = model('app\api\model\wanlshop\Order')->get($order_id,['goods'])->toArray();
        $address = model('app\index\model\wanlshop\OrderAddress')
            ->where(['order_id' => $order_id])
            ->order('isaddress desc')
            ->find();
        $city = explode('/',$address['address'])[1] ?? '';
        $rules = collection(Packagerule::all())->toArray();
        $packageClass = new \fast\Package($order['goods'],$rules);
        $packageList = $packageClass->buildPackage();
        $orderGoods = array_column($order['goods'],null,'goods_sku_id');
        $goodsList = $addressList = $packageData = [];

        $order_a = json_decode($order['attachment'],true);
        //[{"goods":[1280,1452],"phone_price":0.5,"shox_price":1},{"goods":[1450],"phone_price":0.5,"shox_price":0}]
        $g_list = $order['goods'];

        $arr = [];
        foreach ($order_a as $v1){
            foreach ($g_list as $v2){
                if($v1['goods'][0]==$v2['goods_id']){
                    $arr[] = [
                        'goods_sku_id' => $v2['goods_sku_id'],
                        'phone_price'=>$v1['phone_price'],
                        'shox_price'=>$v1['shox_price'],
                    ];
                }
            }
        }

      //  dump($order_a);
     //   dump($arr);
      //  dump($packageList);
     //   die;
        //[{"goods":[1280,1452],"phone_price":0.5,"shox_price":1},{"goods":[1450],"phone_price":0.5,"shox_price":0}]
        foreach ($packageList as $list){
            foreach ($list as $item){
                $package = new Package();
                $package->order_id = $order['id'];
                $package->user_id = $order['user_id'];
                $package->shop_id = $order['shop_id'];
                $package->package_no = $order['shop_id'].$order['user_id'];
                $package->weight = $item['weight'];
                $packageFright = $this->freight($order['freight_id'],$item['weight'],1,$city);
                $package->freight_id = $packageFright['id'];
                $package->freight_price = $packageFright['price'];
                $keys = array_keys($item['goods']);//[1649,1477]

                foreach ($arr as $v4){
                    if(in_array($v4['goods_sku_id'],$keys)){
                        $package->phone_price = $v4['phone_price'];
                        $package->shox_price = $v4['shox_price'];
                    }
                }
                if($package->save()){
                    $package_price = $package_supply_price = $service_price = $settlement_price = 0;
                    foreach ($item['goods'] as $data){
                        // 商品列表 actual_payment
                        $goodsList[] = [
                            'order_id' => $order['id'], // 获取自增ID
                            'order_goods_id' =>$orderGoods[$data['sku_id']]['id'],
                            'package_id' => $package->id,
                            'goods_id' => $orderGoods[$data['sku_id']]['goods_id'],
                            'title' => $orderGoods[$data['sku_id']]['title'],
                            'shop_id' => $orderGoods[$data['sku_id']]['shop_id'],
                            'shop_name' => $orderGoods[$data['sku_id']]['shop_name'],
                            'image' => $orderGoods[$data['sku_id']]['image'],
                            'goods_sku_sn' => $orderGoods[$data['sku_id']]['goods_sku_sn'],
                            'goods_sku_id' => $orderGoods[$data['sku_id']]['goods_sku_id'],
                            'goods_sku_rule_id' => $orderGoods[$data['sku_id']]['goods_sku_rule_id'],
                            'weight' => $orderGoods[$data['sku_id']]['weight'],
                            'difference' => $orderGoods[$data['sku_id']]['difference'],
                            'price' => $orderGoods[$data['sku_id']]['price'],
                            'supply_price' => $orderGoods[$data['sku_id']]['supply_price'],
                            'market_price' => $orderGoods[$data['sku_id']]['market_price'],
                            'number' => $data['order_goods_number'],
                        ];

                        $package_price += bcmul($orderGoods[$data['sku_id']]['price'],$data['order_goods_number'],2);
                        $package_supply_price += bcmul($orderGoods[$data['sku_id']]['supply_price'],$data['order_goods_number'],2);
                        $service_price += 0;
                        $settlement_price +=  bcmul($orderGoods[$data['sku_id']]['price'],$data['order_goods_number'],2) - bcmul($orderGoods[$data['sku_id']]['supply_price'],$data['order_goods_number'],2);
                    }
                    // 生成地址
                    $addressList[] = [
                        'package_id' => $package->id,
                        'user_id' => $address['user_id'],
                        'shop_id' => $address['shop_id'],
                        'order_id'  => $address['order_id'],
                        'isaddress'  => $address['isaddress'],
                        'name' => $address['name'],
                        'mobile' => $address['mobile'],
                        'address' => $address['address'],
                        'address_name' => $address['address_name'],
                        'location' => $address['location'],
                        'image_front' => $address['image_front'],
                        'image_back' => $address['image_back'],
                        'number' => $address['number'],
                    ];
                    $package->package_price = $package_price;
                    $package->package_supply_price = $package_supply_price;
                    $package->service_price = $service_price;
                    $package->settlement_price = $settlement_price;
                    $package->save();
                }

            }
        }

        model('app\api\model\wanlshop\Packageaddress')->saveAll($addressList);
        model('app\api\model\wanlshop\Packagegoods')->saveAll($goodsList);
        Db::commit();
    }


    // 先分包裹算运费
    public function packageFright($products,$freight_id = 3,$city = ''){
        $products = collection($products)->toArray();

        // 首先取sku_id作为key
        $goodsData = [];
        foreach ($products as $product){
            if(isset($product['sku']['id'])){
                $goodsData[$product['sku']['id']] = [
                    'number' => $product['number'],
                    'weight' => $product['sku']['weigh'],
                    'goods_sku_id' => $product['sku']['id'],
                    'goods_sku_rule_id' => $product['sku']['rule_id'],
                ];
            }else{
                $goodsData[$product['goods_sku_id']] = [
                    'number' => $product['number'],
                    'weight' => $product['weight'],
                    'goods_sku_id' => $product['goods_sku_id'],
                    'goods_sku_rule_id' => $product['goods_sku_rule_id'],
                ];
            }

        }
        $skuData = model('app\api\model\wanlshop\GoodsSku')
            ->whereIn('id', array_keys($goodsData))
            ->field('id,difference,difference_en,price,market_price,stock,weigh,group_price,supply_price,rule_id')
            ->order('weigh desc')
            ->select();
        // 组装包裹数据
        $goods = [];
        foreach ($skuData as $sku){
            $goods[] = $goodsData[$sku['id']];
        }
        $rules = collection(Packagerule::all())->toArray();
        $packageClass = new \fast\Package($goods,$rules);
        $packageList = $packageClass->buildPackage();
        $freightPrice = 0;
        $splitPackage = [];
        foreach ($packageList as $list){
            foreach ($list as $item){
                $item['weight'] = round($item['weight'],2);
                $freight = $this->freight($freight_id,$item['weight'],1,$city);
                $freightPrice += $freight['price'];
                $item['freightPrice'] = $freight['price'];
                $item['attachment']=[
                    'phone'=>[
                        'text'=>'拍照标记[AU$ 0.5]',
                        'price'=>0.5,
                    ],
                    'shox'=>[
                        'text'=>'气柱[AU$ 1]',
                        'price'=>1
                    ]
                ];
                foreach ($item['goods'] as $key => $goods){
                    $sku = model('app\api\model\wanlshop\GoodsSku')->where('id',$goods['sku_id'])->find();
                    $item['goods'][$key]['sku'] = is_array($sku['difference']) ? implode(';',$sku['difference']) : $sku['difference'];
                    $item['goods'][$key]['name'] = model('app\api\model\wanlshop\Goods')->where('id',$sku['goods_id'])->value('title');
                }
                $splitPackage[] = $item;
            }
        }
        return [
            'packageList' => $splitPackage,
            'freightPrice' => $freightPrice,
        ];
    }


    /**
     * 获取运费模板和子类 内部方法
     * @param string $id  运费ID
     * @param string $weigh  商品重量
     * @param string $number  商品数量
     * @param string $city  邮递城市
     */
    private function freight($id = null, $weigh = null, $number = 0, $city = null)
    {
        if(!$id){ // 如果id为0则为自提,默认返回数据
            return [
                'id' =>0,
                'name' =>0,
                'price' => 0,
                'isdelivery' => 0,
            ];
        }
        // 运费模板
        $data = model('app\api\model\wanlshop\ShopFreight')->where('id', $id)->field('id,delivery,isdelivery,name,valuation')->find();
        $data['price'] = 0;
        // 是否包邮:0=自定义运费,1=卖家包邮
        if($data['isdelivery'] == 0){
            // 获取地址编码
            $area = model('app\common\model\Area')->where('name',$city)->find();
            /*$list = model('app\api\model\wanlshop\ShopFreightData')
                ->where('citys','like','%'.$area['id'].'%')
                ->where('freight_id',$id)
                ->find();*/
            $list = model('app\api\model\wanlshop\ShopFreightData')
                ->where([
                    ['exp', Db::raw("FIND_IN_SET({$area['id']},citys)")],
                    'freight_id'=>$id
                ])
                ->find();
            // 查询是否存在运费模板数据
            if(!$list){
                $list = model('app\api\model\wanlshop\ShopFreightData')
                    ->where('freight_id',$id)
                    ->find();
            }
            // 计价方式:0=按件数,1=按重量,2=按体积  1.0.2升级
            if($data['valuation'] == 0){
                if($number <= $list['first']){
                    $price = $list['first_fee'];
                }else{
                    $additional = $list['additional'] > 0 ? $list['additional'] : 1; //因为要更换vue后台，临时方案，为防止客户填写0
                    $price = bcadd(bcmul(ceil(($number - $list['first']) / $additional), $list['additional_fee'], 2), $list['first_fee'], 2);
                }
            }else{
                $weigh = $weigh * $number; // 订单总重量
                if($weigh <= $list['first']){ // 如果重量小于等首重，则首重价格
                    $price = $list['first_fee'];
                }else{
                    $additional = $list['additional'] > 0 ? $list['additional'] : 1;
                    $price = bcadd(bcmul(ceil(($weigh - $list['first']) / $additional), $list['additional_fee'], 2), $list['first_fee'], 2);
                }
            }
            $data['price'] = $price;
        }
        return $data;
    }

}
